/*
 * @Author: 脉迈
 * @Date: 2022-01-22 16:05:04
 * @LastEditors: 脉迈
 * @LastEditTime: 2022-01-22 18:21:31
 */
import React from "react";
import { Route, Redirect } from "react-router-dom";
import { useRecoilState } from "recoil";
import { userRouters } from "store/modules/user";
import { getLocal } from "utils/helper";
import { getRouters } from "api/user";
const AuthRouter = (props: any) => {
  // 路由权限，目前写死，实际项目请让服务端返回
  const { path, component, exact } = props;
  const [userRoutersList, setUserRoutersList] = useRecoilState(userRouters);
  
  const loadRouter = () => {
    // 请求路由接口，拿取路由权限
    // 1. 访问状态管理，是否有路由权限列表，如有则直接跳转，否则进行第二步
    // 2. 如果路由列表返回没有权限，则跳转('404'),有权限就直接访问
    if (userRoutersList.length) {
      if (userRoutersList.includes(path)) {
        return <Route path={path} component={component} exact={exact}></Route>;
      } else {
        return <Redirect to="/404" />;
      }
    } else {
      getRouters().then((res: any) => {
        let { data } = res;
        setUserRoutersList(data);
        if (data.includes(path)) {
          return (
            <Route path={path} component={component} exact={exact}></Route>
          );
        } else {
          return <Redirect to="/404" />;
        }
      });
    }
  };
  return (
    <>
      {getLocal("ACCESS_TOKEN") ? 
        loadRouter()
      : (
        <Redirect to="/login" />
      )}
    </>
  );
};

export default AuthRouter;
